<template>
  <div>
    <div>
      <el-switch v-model="draggable" active-text="开启拖拽" inactive-text="关闭拖拽">
      </el-switch>
      <el-button v-if="draggable" type="success" @click="save">批量保存
      </el-button>
      <el-button type="danger" @click="menusDelete">删除</el-button>
      <el-tree :expand-on-click-node="false" :data="menus" show-checkbox :draggable="draggable" node-key="catId"
        :allow-drop="allowDrop" :default-expanded-keys="expandedKeys" :props="defaultProps" @node-drop="handleDrop"
        ref="refsTree">
        <span class="custom-tree-node" slot-scope="{ node, data }">
          <span>{{ node.label }}</span>
          <span>
            <el-button v-if="node.level <= 2" type="text" size="mini" @click="() => append(data)">
              新增
            </el-button>

            <el-button type="text" size="mini" @click="() => edit(data)">
              修改
            </el-button>

            <el-button v-if="node.childNodes.length == 0" type="text" size="mini" @click="() => remove(node, data)">
              删除
            </el-button>
          </span>
        </span>
      </el-tree>
      <el-dialog :title="title" :visible.sync="dialogFormVisible" width="30%" :close-on-click-modal="false">
        <el-form :model="category">
          <el-form-item label="菜单名称">
            <el-input v-model="category.name" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="图标">
            <el-input v-model="category.icon" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="计量单位">
            <el-input v-model="category.productUnit" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="
            dialogFormVisible = false;
          category.name = '';
          ">取 消
          </el-button>
          <el-button type="primary" @click="subMitCategory">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      isSave: false,
      pCid: [],
      draggable: false,
      updataLevel: [],
      maxlevel: 0,
      diologType: "",
      title: "",
      category: {
        name: "",
        showStatus: 1,
        sort: 0,
        productCount: 0,
        catLevel: 0,
        parentCid: 0,
        icon: "",
        catId: null,
        productUnit: "",
      },
      dialogFormVisible: false,
      menus: [],
      expandedKeys: [],
      defaultProps: {
        children: "children",
        label: "name",
      },
    };
  },
  created() {
    this.getMenus();
  },
  methods: {
    menusDelete() {
      let checkedNodes = this.$refs.refsTree.getCheckedNodes();
      let ids = [];
      let names = [];
      for (let i = 0; i < checkedNodes.length; i++) {
        ids.push(checkedNodes[i].catId);
        names.push(checkedNodes[i].name);
      }
      this.$confirm(`此操作将永久删除【${names}】, 是否继续?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$http({
            url: this.$http.adornUrl("/product/category/delete"),
            method: "post",
            data: this.$http.adornData(ids, false),
          }).then(({ data }) => {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            //重新获取数据
            this.getMenus();
          });
        })
        .catch(() => {
        });
    },
    save() {
      this.$http({
        url: this.$http.adornUrl("/product/category/update/sort"),
        method: "post",
        data: this.$http.adornData(this.updataLevel, false),
      }).then(({ data }) => {
        this.$message({
          type: "success",
          message: "修改成功!",
        });
        this.expandedKeys = this.pCid;
        this.updataLevel = [];
        this.maxlevel = 0;
        this.isSave = true;
        //重新获取数据
        this.getMenus();
      });
    },
    handleDrop(draggingNode, dropNode, dropType) {
      let pCid = 0;
      let siblings = null;
      if (dropType == "before" || dropType == "after") {
        pCid =
          dropNode.parent.data.catId == undefined
            ? 0
            : dropNode.parent.data.catId;
        siblings = dropNode.parent.childNodes;
      } else {
        pCid = dropNode.data.catId;
        siblings = dropNode.childNodes;
      }
      if (this.isSave) {
        this.pCid = [];
        this.pCid.push(pCid);
        this.isSave = false;
      } else {
        this.pCid.push(pCid);
      }
      for (let i = 0; i < siblings.length; i++) {
        if (siblings[i].data.catId == draggingNode.data.catId) {
          let catLevel = draggingNode.data.catLevel;
          if (siblings[i].level != draggingNode.data.catLevel) {
            catLevel = siblings[i].level;
            this.updataChildNodeLevel(siblings[i]);
          }
          this.updataLevel.push({
            catId: siblings[i].data.catId,
            sort: i,
            parentCid: pCid,
            catLevel: catLevel,
          });
        } else {
          this.updataLevel.push({ catId: siblings[i].data.catId, sort: i });
        }
      }
    },
    updataChildNodeLevel(node) {
      if (node.childNodes.length > 0) {
        for (let i = 0; i < node.childNodes.length; i++) {
          this.updataLevel.push({
            catId: node.childNodes[i].data.catId,
            catLevel: node.childNodes[i].level,
          });
          this.updataChildNodeLevel(node.childNodes[i]);
        }
      }
    },
    subMitCategory() {
      if (this.diologType === "edit") {
        this.updataCategory();
      }
      if (this.diologType === "add") {
        this.addCategory();
      }
    },
    allowDrop(draggingNode, dropNode, type) {
      this.countnodelevel(draggingNode);
      let deep = this.maxlevel - draggingNode.level + 1;
      if (type == "inner") {
        return deep + dropNode.level <= 3;
      } else {
        return deep + draggingNode.parent.level <= 3;
      }
    },
    countnodelevel(draggingNode) {
      if (
        draggingNode.childNodes != null &&
        draggingNode.childNodes.length > 0
      ) {
        for (let i = 0; i < draggingNode.childNodes.length; i++) {
          if (draggingNode.childNodes[i].level > this.maxlevel) {
            this.maxlevel = draggingNode.childNodes[i].level;
          }
          this.countnodelevel(draggingNode.childNodes[i]);
        }
      }
    },
    updataCategory() {
      var { catId, name, icon, productUnit } = this.category;
      this.$http({
        url: this.$http.adornUrl("/product/category/update"),
        method: "post",
        data: this.$http.adornData({ catId, name, icon, productUnit }, false),
      }).then(({ data }) => {
        this.$message({
          type: "success",
          message: "修改成功!",
        });
        this.expandedKeys = [this.category.parentCid];

        this.dialogFormVisible = false;
        //重新获取数据
        this.getMenus();
      });
    },
    getMenus() {
      this.$http({
        url: this.$http.adornUrl("/product/category/list/tree"),
        method: "get",
      }).then(({ data }) => {
        this.menus = data.data;
      });
    },
    edit(data) {
      this.title = "修改";
      this.diologType = "edit";
      this.$http({
        url: this.$http.adornUrl(`/product/category/info/${data.catId}`),
        method: "get",
      }).then(({ data }) => {
        this.category.catId = data.category.catId;
        this.category.name = data.category.name;
        this.category.icon = data.category.icon;
        this.category.parentCid = data.category.parentCid;
        this.category.productUnit = data.category.productUnit;
      });
      this.dialogFormVisible = true;
    },
    append(data) {
      this.diologType = "add";
      this.title = "新增";

      this.category.name = "";
      this.category.icon = "";
      this.category.productCount = 0;
      this.category.productUnit = "";
      this.category.showStatus = 1;
      this.category.sort = 0;
      this.category.catId = null;
      this.category.catLevel = data.catLevel * 1 + 1;
      this.category.parentCid = data.catId;
      this.dialogFormVisible = true;
    },

    addCategory() {
      this.$http({
        url: this.$http.adornUrl("/product/category/save"),
        method: "post",
        data: this.$http.adornData(this.category, false),
      }).then(({ data }) => {
        this.$message({
          type: "success",
          message: "保存成功!",
        });
        this.expandedKeys = [this.category.parentCid];
        this.dialogFormVisible = false;
        //重新获取数据
        this.getMenus();
      });
    },

    remove(node, data) {
      var ids = [data.catId];
      console.log(data);
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$http({
            url: this.$http.adornUrl("/product/category/delete"),
            method: "post",
            data: this.$http.adornData(ids, false),
          }).then(({ data }) => {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            this.expandedKeys = [node.parent.data.catId];
            //重新获取数据
            this.getMenus();
          });
        })
        .catch(() => {
        });
    },
  },
};
</script>

<style lang="scss" scoped></style>
